import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


public class WebServer{
	public static void main(String argv[]) throws Exception{
		int port=6789;
		//establish listen socket
		ServerSocket listen = new ServerSocket(port);
		while (true){
			//listen for TCP connection request
			Socket connection = listen.accept();
			//Construct object to process HTTP request message
			TagRequest request = new TagRequest(connection);
			//Create a new thread to process the request
			(new Thread(request)).start();	
		}
	}
}
class TagRequest implements Runnable{
	final static String nl="\r\n";
	Socket socket;

	public TagRequest(Socket s) throws Exception{
		this.socket=s;
	}
	public void run(){
		try{
			processRequest();
			socket.close();
		} catch (Exception e){
			System.out.println(e);
		}
	}
	void processRequest() throws Exception{
		//Get reference to socket's i and o streams
		InputStream is = socket.getInputStream();
		DataOutputStream os = new DataOutputStream(socket.getOutputStream());

		//Set up input stream filters
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String requestLine = br.readLine();
		if (requestLine.equals("query")){
			System.out.println("got a query");
			String tagsList = new String("");
			FileReader tagsFileReader = new FileReader("tagsFile");
			BufferedReader readFromFile = new BufferedReader(tagsFileReader);
			String tagLine = null;
			while ((tagLine = readFromFile.readLine()) != null){
				tagsList = tagsList.concat(tagLine + nl);
			}
			os.writeBytes(tagsList);
			
			System.out.println("Sending to App:" + nl + tagsList);
			
			readFromFile.close();
			tagsFileReader.close();
		}
		else{
			System.out.println("got something other than a query");
			FileWriter tagsFileWriter = new FileWriter("tagsFile",true);
			BufferedWriter writeToFile = new BufferedWriter(tagsFileWriter);
			writeToFile.write(requestLine + nl);
			
			System.out.println("Adding to File: " + requestLine + nl);
			
			writeToFile.close();
			tagsFileWriter.close();
		}
		os.close();
		br.close();
		is.close();
	}
}